/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.camachosanchez.gui;

import com.camachosanchez.bean.InsumosDespinche;
import com.camachosanchez.controler.jdbc.InsumosJdbcControler;
import com.camachosanchez.controler.jpa.InsumosDespincheJpaController;
import com.camachosanchez.gui.textfield.MaxLengthTextDocument;
import com.camachosanchez.util.Constantes;
import com.camachosanchez.util.EstadosJDialog;
import com.camachosanchez.util.GUIUtil;
import java.awt.event.KeyEvent;
import javax.swing.JOptionPane;

/**
 *
 * @author ZULLY
 */
public class EditorInsumoDespinche extends javax.swing.JDialog {

    public EstadosJDialog.EstadoJDialog Estado;
    private MaestroInsumosDespinche buscador;
    private int fila;
    private InsumosDespinche insumo;

    /**
     * Creates new form EditorInsumoDespinche
     */
    public EditorInsumoDespinche(MaestroInsumosDespinche buscador, java.awt.Frame parent, boolean modal, InsumosDespinche insumo, int fila) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        GUIUtil.addEscapeKey(this);
        this.buscador = buscador;
        this.fila = fila;
        
        txtCodigo.requestFocusInWindow();
        MaxLengthTextDocument docCodigo = new MaxLengthTextDocument();
        docCodigo.setMaxChars(10, Constantes.ENTEROS);
        txtCodigo.setDocument(docCodigo);
        
        if (insumo != null) {
            this.CargarDatosInsumo(insumo);
            this.insumo = insumo;
        }
    }

    private void CargarDatosInsumo(InsumosDespinche insumo) {
        txtCodigo.setText("" + insumo.getCodigo());
        txtNombre.setText(insumo.getNombre());
    }

    public EstadosJDialog.EstadoJDialog getEstado() {
        return Estado;
    }

    public void setEstado(EstadosJDialog.EstadoJDialog Estado) {
        switch (Estado) {
            case NUEVO:
                btnEliminar.setVisible(false);
                break;
            case MODIFICAR:
                btnEliminar.setVisible(true);
                break;
        }
        this.Estado = Estado;
    }

    private void GuardarDatos() {
        switch (this.Estado) {
            case NUEVO:
                RegistrarInsumo(LeerDatosInsumo());
                break;
            case MODIFICAR:
                ModificarInsumo(LeerDatosInsumo());
                break;
            case ELIMINAR:
                break;
            default:
                break;
        }
    }

    private boolean ValidarDatos() {
        if (txtCodigo.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Se requiere un código para el insumo de despinche.", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
            txtCodigo.requestFocusInWindow();
            return false;
        }
        if (this.txtNombre.getText().isEmpty()) {
            JOptionPane.showMessageDialog(this, "Se requiere un nombre para el insumo de despinche.", "Datos incompletos", JOptionPane.WARNING_MESSAGE);
            txtNombre.requestFocusInWindow();
            return false;
        }
        return true;
    }

    private InsumosDespinche LeerDatosInsumo() {
        InsumosDespinche i = new InsumosDespinche();
        i.setCodigo(Integer.parseInt(txtCodigo.getText().trim()));
        i.setNombre(txtNombre.getText().trim());
        if (this.insumo != null) {
            i.setDetalleDespincheList(this.insumo.getDetalleDespincheList());
        }
        return i;
    }

    private void RegistrarInsumo(InsumosDespinche insumo) {
        InsumosDespincheJpaController dao_insumo = new InsumosDespincheJpaController(null);
        insumo.setEstado(true);
        dao_insumo.create(insumo);
        JOptionPane.showMessageDialog(this, "El insumo de despinche ha sido guardado correctamente.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
        buscador.llenarInsumos();
        this.dispose();
    }

    private void ModificarInsumo(InsumosDespinche insumo) {
        InsumosDespincheJpaController dao_insumo = new InsumosDespincheJpaController(null);
        try {
            insumo.setEstado(true);
            insumo.setId(this.insumo.getId());
            dao_insumo.edit(insumo);
            JOptionPane.showMessageDialog(this, "Los datos del insumo de despinche han sido actualizados correctamente.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
            buscador.llenarInsumos();
            dispose();
        } catch (Exception e) {
            JOptionPane.showMessageDialog(Principal.getInstance(), e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnlToolBar = new javax.swing.JPanel();
        btnGuardar = new javax.swing.JButton();
        btnEliminar = new javax.swing.JButton();
        pnlContenedor = new javax.swing.JPanel();
        lblNombre = new javax.swing.JLabel();
        txtCodigo = new javax.swing.JTextField();
        lblIniciales = new javax.swing.JLabel();
        txtNombre = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle(".:: Insumo de Despinche ::.");
        setMinimumSize(new java.awt.Dimension(400, 108));
        setResizable(false);

        pnlToolBar.setBackground(new java.awt.Color(255, 255, 255));
        pnlToolBar.setLayout(new java.awt.FlowLayout(java.awt.FlowLayout.LEFT));

        btnGuardar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_save.png"))); // NOI18N
        btnGuardar.setToolTipText("Guardar");
        btnGuardar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnGuardar.setFocusable(false);
        btnGuardar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnGuardar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnGuardar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnGuardar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnGuardarActionPerformed(evt);
            }
        });
        pnlToolBar.add(btnGuardar);

        btnEliminar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/camachosanchez/recursos/24_delete.png"))); // NOI18N
        btnEliminar.setToolTipText("Eliminar");
        btnEliminar.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        btnEliminar.setFocusable(false);
        btnEliminar.setHorizontalTextPosition(javax.swing.SwingConstants.RIGHT);
        btnEliminar.setMaximumSize(new java.awt.Dimension(22, 22));
        btnEliminar.setMinimumSize(new java.awt.Dimension(22, 22));
        btnEliminar.setPreferredSize(new java.awt.Dimension(22, 22));
        btnEliminar.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });
        pnlToolBar.add(btnEliminar);

        getContentPane().add(pnlToolBar, java.awt.BorderLayout.PAGE_START);

        lblNombre.setText("<html>Código: <font color=\"red\">(*)</font> </html>");

        txtCodigo.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtCodigoKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtCodigoKeyTyped(evt);
            }
        });

        lblIniciales.setText("<html>Nombre: <font color=\"red\">(*)</font> </html>");

        txtNombre.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txtNombreKeyPressed(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                txtNombreKeyTyped(evt);
            }
        });

        javax.swing.GroupLayout pnlContenedorLayout = new javax.swing.GroupLayout(pnlContenedor);
        pnlContenedor.setLayout(pnlContenedorLayout);
        pnlContenedorLayout.setHorizontalGroup(
            pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnlContenedorLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(pnlContenedorLayout.createSequentialGroup()
                        .addComponent(lblIniciales, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 309, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(pnlContenedorLayout.createSequentialGroup()
                        .addComponent(lblNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, 117, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(19, Short.MAX_VALUE))
        );
        pnlContenedorLayout.setVerticalGroup(
            pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnlContenedorLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(txtCodigo, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnlContenedorLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtNombre, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lblIniciales, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(14, Short.MAX_VALUE))
        );

        getContentPane().add(pnlContenedor, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnGuardarActionPerformed
        // TODO add your handling code here:
        if (ValidarDatos()) {
            GuardarDatos();
        }
    }//GEN-LAST:event_btnGuardarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        if (JOptionPane.showConfirmDialog(null, "¿Está seguro que desea eliminar el insumo de despinche seleccionado?", "Confirmación", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_NO_OPTION) {
            int id = this.insumo.getId();
            InsumosJdbcControler daoJdbc = new InsumosJdbcControler();
            byte estado = daoJdbc.eliminarInsumo(id);
            if (estado == 1) {
                JOptionPane.showMessageDialog(this, "El insumo de despinche se encuentra relacionado con otros registros, no puede ser eliminada.", "Error en la eliminación", JOptionPane.ERROR_MESSAGE);
            } else {
                JOptionPane.showMessageDialog(this, "El insumo de despinche se ha eliminado de forma segura.", "Operación finalizada", JOptionPane.INFORMATION_MESSAGE);
                buscador.borrarInsumo(fila);
                dispose();
            }
        }
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void txtCodigoKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            txtNombre.requestFocusInWindow();
        }
    }//GEN-LAST:event_txtCodigoKeyPressed

    private void txtCodigoKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtCodigoKeyTyped
        // TODO add your handling code here:
        char caracter = evt.getKeyChar();
        if (((caracter < '0') || (caracter > '9')) && (caracter != '\b' /*corresponde a BACK_SPACE*/)) {
            evt.consume();
        }
        String caracteres = txtCodigo.getText();
        if (caracteres.length() >= 5) {
            evt.consume();
        }
    }//GEN-LAST:event_txtCodigoKeyTyped

    private void txtNombreKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
            btnGuardar.requestFocusInWindow();
        }
    }//GEN-LAST:event_txtNombreKeyPressed

    private void txtNombreKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txtNombreKeyTyped
        // TODO add your handling code here:
        String caracteres = txtNombre.getText();
        if (caracteres.length() >= 60) {
            evt.consume();
        }
    }//GEN-LAST:event_txtNombreKeyTyped
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnGuardar;
    private javax.swing.JLabel lblIniciales;
    private javax.swing.JLabel lblNombre;
    private javax.swing.JPanel pnlContenedor;
    private javax.swing.JPanel pnlToolBar;
    private javax.swing.JTextField txtCodigo;
    private javax.swing.JTextField txtNombre;
    // End of variables declaration//GEN-END:variables
}
